﻿@model Nop.Web.Models.ShareBuy.ShareBuyModel
@using Nop.Web.Framework
@using Nop.Web.Models.ShareBuy;
@using Telerik.Web.Mvc.UI;
@Html.ValidationSummary(true)
@{
    //register CSS and JS
    Html.AddCssFileParts(@Url.Content("~/Administration/Content/uploadify.css"));
    Html.AddScriptParts(@Url.Content("~/Administration/Scripts/swfobject.js"));
    Html.AddScriptParts(@Url.Content("~/Administration/Scripts/jquery.uploadify.v2.1.4.min.js"));

}

<script type="text/javascript">
    var authToken = '@(this.Context.Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)';
    var pictureTemplate="<li>"+
            "<div class='s-img'>"+
                "<img width='300' src='{#imageUrl}'><input type='hidden' class='hidPictureId' value='{#PictureId}' /></div>"+
            "<div class='s-set'>"+
                    "<div>"+
                        "<input type='radio' checked='checked' class='cover' value='{#PictureId}' name='cover' id='rad{#PictureId}'><label for='rad{#PictureId}'>Set to cover</label></div>"+
                    "<div class='set-item'>"+
                        "<label>Order</label>"+
                        "<input class='order' type='text' value='0' />"+
                    "</div>"+
                    "<div class='set-item'>"+
                        "<input type='button' value='Delete' class='del' shareBuyPictureId='0' pictureId='{#PictureId}' onclick='deletePictureItem(this)'></div>"+
            "</div>"+
            "</li>";
    $(document).ready(function () {
        $('#addShareBuy').click(function () {
            //validate
            if($.trim($("#ProductVariants").val())=="")
            {
                alert("Product is requested.");
                return;
            }
            if($.trim($("#Title").val())==""){
                alert("Title is requested.");
                return;
            }
            if($("#pictureSets li").length<3||$("#pictureSets li").length>10) {
                alert("Please upload 3-10 pictures.");
                return;
            }
            saveShareBuy();
        });

        $("#uploadPicture").uploadify({

             'uploader': '@(Url.Content("~/Content/Flash/uploadify.swf"))',
                'script': '@(Url.Content("~/Admin/Picture/AsyncUpload"))',
                "scriptData": { authToken: authToken },
                'cancelImg': '@Url.Content("~/Administration/Content/images/cancel-uploading.png")',
                'folder': '',
                'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
                "buttonText": "Upload",
                'sizeLimit': 1024 * 1024 * 15,//15M
                'fileDesc': '*.jpg;*.jpeg;*.gif;*.png',
                'simUploadLimit': 1,
                'queueSizeLimit': 1,
                'auto': true,
                'multi': false,
                'onComplete': function(e, queueId, fileObj, response, data) {
                    var json = jQuery.parseJSON(response);
                    if (json.success) {
                        var pictureItemHtml=pictureTemplate.replace(new RegExp("{#PictureId}",'g'),json.pictureId);
                        pictureItemHtml=pictureItemHtml.replace(new RegExp("{#imageUrl}",'g'),json.imageUrl);
                        $("#pictureSets").append(pictureItemHtml);
                    } else {
                        alert(json.error);
                    }
                },
                'onError': function(a, b, c, d) {
                    if (d.status == 404)
                        alert('Upload script no found: ' + '<?= getcwd() ?>');
                    else if (d.type === "HTTP")
                        alert('error： ' + d.type + ": " + d.status);
                    else if (d.type === "File Size")
                        alert(c.name + ' ，Over max size： ' + iMaxUpdateFileSize / 1024 + 'KB');
                    else
                        alert('error： ' + d.type + ": " + d.info);
                }
        });
    });

    function deletePictureItem(btnObj)
    {
        if(confirm("Sure delete?"))
        {
            var shareBuyPictureId=$(btnObj).attr("shareBuyPictureId");
            var pictureId=$(btnObj).attr("pictureId");
            var url="";
            var data="";
            if(shareBuyPictureId>0)
            {
                url="@Url.Content("~/sharebuypicture/delete/")"+shareBuyPictureId;
            }
            else
            {
                url="@Url.Content("~/picture/delete/")"+pictureId;
            }

            $(btnObj).attr('disabled', true);
            $.ajax({
                cache:false,
                type: "POST",
                url: url,
                data:data,
                success: function (data) {
                        if(data.Result)
                        {
                            alert("Delete successfully.")
                            var li=$(btnObj).parent().parent().parent();
                            if(li.find(".cover").attr("checked")=="checked")
                            {
                                $("#pictureSets li .cover:first").attr("checked","checked");
                            }
                            li.remove();

                        }
                        else
                        {
                            alert('Failed to delete picture.')
                        }
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert('Failed to delete picture.')
                        $(btnObj).attr('disabled', false);
                    }  
                });
            
        }
    }

    function saveShareBuy()
    {
        $("#addShareBuy").attr("disabled","disabled");
        var title=$.trim($("#Title").val());
        var description=$.trim($("#Description").val());
        var picturesJSON=getPicturesJSON();
        var productVariantId=$("#ProductVariants").val();
        var categoryId=$("#Categories").val();

        $(this).attr('disabled', true);
        $.ajax({
            cache:false,
            type: "POST",
            url: "@Url.Action("Save", "ShareBuy")",
            data: { "id": @Model.Id,"categoryId":categoryId, "productVariantId": productVariantId, "cutomerId": @Model.CustomerId,"title":title,"description":description,"picturesJSON":picturesJSON,"defaultPictureId":$("#pictureSets input[name='cover']:checked").val() },
            success: function (data) {
                    if(data.Result)
                    {
                        window.location.href="/sharebuy/detail/"+data.Id;
                        $(this).attr('disabled', false);
                    }
                    else
                    {
                        alert('Failed to add Sharing.')
                    }
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert('Failed to add Sharing.')
                    $(this).attr('disabled', false);
                }  
            });
    }

    function getPicturesJSON()
    {
        var ret="[";
        var items="";
        $("#pictureSets li").each(function(){
            items=items+"{\"PictureId\":"+$(this).find(".hidPictureId").val()+",\"PictureUrl\":\""+$(this).find(".s-img img").attr("src")+"\",\"DisplayOrder\":"+$.trim($(this).find(".order").val())+"},";
        });
        if(items!="")
        {
            items=items.substring(0,items.length-1);
        }
        ret=ret+items+"]";
        return ret;
    }
</script>
<div class="w">

    <div class="w">
        <div id="show" class="m">
            <div class="mt">
                <h2>
                    Share</h2>
            </div>
            <div class="mc">
                <div class="o-item">
                    <div class="item fore  ">
                        <div class="tit">
                            @Html.LabelFor(model => model.ProductVariantSelectList)<s>*</s>:
                            </div>
                        <div class="i-item">
                            @Html.DropDownList("ProductVariants", Model.ProductVariantSelectList, "Choose an product")
                        </div>
                    </div>
                    <div class="item">
                        <div class="tit">
                            @Html.LabelFor(model => model.CategorySelectList)<s>*</s>:
                            </div>
                        <div class="i-item">
                            @Html.DropDownList("Categories", Model.CategorySelectList, "Choose an category")
                        </div>
                    </div>
                    <div class="item">
                        <div class="tit">
                            @Html.LabelFor(model => model.Title)<s>*</s>:</div>
                        <div class="i-item">
                            @Html.EditorFor(model => model.Title)
                            @Html.ValidationMessageFor(model => model.Title)
                        </div>
                    </div>
                    <div class="item text">
                        <div class="tit">
                            @Html.LabelFor(model => model.Description):</div>
                        <div class="i-item">
                            @Html.TextAreaFor(model => model.Description, new { style = "Width: 580px; Height: 150px;" })
                            @Html.ValidationMessageFor(model => model.Description)
                            <div id="v_c" class="tips">
                                You can input 1000 words at most, including a blank space.
                            </div>
                        </div>
                    </div>
                    <div class="item">
                        <div class="tit">
                            Pictures:<s>*</s></div>
                        <div class="i-item">
                            <div>
                                <input type="file" id="uploadPicture" /></div>
                            <div class="tips">
                                Please upload 3-10 pictures. Each picture not more than 15 m, support picture format
                                for JPG, jpeg, BMP, PNG, GIF.</div>
                        </div>
                    </div>
                    <div class="item">
                        <!--Pictures list start!-->
                        <div class="i-item">
                            <ul id="pictureSets" class="s-list">
                                @if (Model.ShareBuyPictureModels.Count > 0)
                                {
                                    foreach (var picture in Model.ShareBuyPictureModels)
                                    {
                                    <li>
                                        <div class="s-img">
                                            <img width="300" src="@picture.PictureUrl"><input
                                                    type="hidden" value="@picture.PictureId" class="hidPictureId"></div>
                                        <div class="s-set">
                                            <div>
                                                <input type="radio" id="rad#@picture.PictureId" name="cover" value="@picture.PictureId" class="cover" @if (picture.PictureId == Model.DefaultPictureId)
                                                                                                                                                      {@Html.Raw("checked='checked'");
                                                                                                                                                      }><label
                                                        for="rad#@picture.PictureId">Set to cover</label></div>
                                            <div class="set-item">
                                                <label>
                                                    Order</label><input type="text" value="@picture.DisplayOrder" class="order"></div>
                                            <div class="set-item">
                                                <input type="button" onclick="deletePictureItem(this)" shareBuyPictureId="@picture.Id" pictureId="@picture.PictureId" class="del" value="Delete"></div>
                                        </div>
                                    </li>
                                    }
                                }
                            </ul>
                        </div>
                        <!--Pictures list end!-->
                    </div>
                    <div class="item">
                        <div class="i-item">
                            <button id="addShareBuy" class="release" value="Submit" name="save" type="button">
                                    Submit</button>
                        </div>
                    </div>
                </div>
                <div class="expl">
                    <h3>
                        About Sharing：</h3>
                    <ul>
                        <li>You can feel the use of choose and buy suggest real photos usage scenario unpacking
                            process with net friends share;</li>

                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
